//
//  Register.m
//  DaoZiJinFu
//
//  Created by woker on 16/7/1.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "Register.h"
#import "ProtocolVC.h"

#define timeOutLine 60

@interface Register () {
    NSInteger timeCount;
    NSTimer *timer;
}

@end

@implementation Register

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"注册"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    
    _registerBtn.layer.masksToBounds = YES;
    _registerBtn.layer.cornerRadius = BTN_RADIUS;
    _agreeBtn.selected = YES;
    _sendCode.layer.masksToBounds = YES;
    _sendCode.layer.cornerRadius = BTN_RADIUS;
    _sendCode.layer.borderWidth = 1;
    _sendCode.layer.borderColor = BLUE_COLOR.CGColor;
    
    _telNumLab.text = [NSString stringWithFormat:@"%@ %@ %@",[_telNum substringWithRange:NSMakeRange(0, 3)],[_telNum substringWithRange:NSMakeRange(3, 4)],[_telNum substringWithRange:NSMakeRange(7, 4)]];
    
    timeCount = timeOutLine;
    
    [self sendCodeClick];
    
    [_sendCode addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sendCodeClick)]];
    
    [_readProtocol addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(turnToReadProtocol)]];
}

- (void)turnToReadProtocol {
    ProtocolVC *protocol = [[ProtocolVC alloc] init];
    protocol.protocolType = 1;
    [self.navigationController pushViewController:protocol animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _msgCode.text = @"";
    _pwdText.text = @"";
    _registerBtn.userInteractionEnabled = NO;
    _registerBtn.backgroundColor = UNUSEABLECOLOR;
}

- (IBAction)visibleClick:(id)sender {
    if (_pwdText.secureTextEntry) {
        [_visibleBtn setBackgroundImage:[UIImage imageNamed:@"显示"] forState:UIControlStateNormal];
    } else {
        [_visibleBtn setBackgroundImage:[UIImage imageNamed:@"不显示"] forState:UIControlStateNormal];
    }
    _pwdText.secureTextEntry = !_pwdText.secureTextEntry;
}

- (IBAction)registerClick:(id)sender {
    if (![self judgePassWordLegal:_pwdText.text]) {
        JSSHOW(@"密码要设为6-20位数字、字母组合。");
        return;
    }
    [self getRnsAndSid];
    [self registerAction];
}

- (void)getRnsAndSid {
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"index/index";
    [DZNetAPI request:request success:^(id result) {
        if ([result[@"rt"] integerValue] == 1) {
            [theUser setObject:result[HKNAME] forKey:HKNAME];
            if (result[@"data"][RNS])[theUser setObject:result[@"data"][RNS] forKey:RNS];
            if (result[@"data"][SID])[theUser setObject:result[@"data"][SID] forKey:SID];
            [theUser synchronize];
        }
    } failure:^(NSError *error) {
    }];
}

- (void)registerAction {
    DZSHOWHUD;
    DZRegisterRequest *request = [[DZRegisterRequest alloc] init];
    request.mobile = _telNum;
    request.pwd = _pwdText.text;
    request.verify_code = _msgCode.text;
    [DZNetAPI request:request success:^(id result) {
        DZHIDEHUD;
        if ([result[@"rt"] integerValue] == 1) {
            JSSHOW(result[@"msg"]);
            [CommTools setUserInfo:result];
            if (!userValue(HAVEGESTUREPWD)) {
                [theUser setObject:[NSNumber numberWithInteger:0] forKey:HAVEGESTUREPWD];
            }
            [theUser setObject:result[@"data"][@"uInfo"][MOBILE] forKey:HOSTTEL];
            [theUser setObject:result[@"data"][@"uInfo"][LOGIN_TOKEN] forKey:LOGIN_TOKEN];
            [theUser setObject:[NSNumber numberWithBool:YES] forKey:ISLOGIN];
            [theUser synchronize];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            JSSHOW(result[@"msg"]);
        }
    } failure:^(NSError *error) {
        DZHIDEHUD;
        JSSHOWTIME(LOAD_FAIL_TIP);
    }];
}

- (IBAction)agreeClick:(id)sender {
    _agreeBtn.selected = !_agreeBtn.selected;
    if (_agreeBtn.selected) {
        [_agreeBtn setImage:[UIImage imageNamed:@"选择"] forState:UIControlStateNormal];
    } else {
        [_agreeBtn setImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
    }
    if (_msgCode.text.length && _pwdText.text.length && _agreeBtn.selected) {
        _registerBtn.backgroundColor = BLUE_COLOR;
        _registerBtn.userInteractionEnabled = YES;
    } else {
        _registerBtn.backgroundColor = UNUSEABLECOLOR;
        _registerBtn.userInteractionEnabled = NO;
    }
}

- (IBAction)codeValueChanged:(id)sender {
    if (_msgCode.text.length && _pwdText.text.length && _agreeBtn.selected) {
        _registerBtn.backgroundColor = BLUE_COLOR;
        _registerBtn.userInteractionEnabled = YES;
    } else {
        _registerBtn.backgroundColor = UNUSEABLECOLOR;
        _registerBtn.userInteractionEnabled = NO;
    }
}

- (IBAction)pwdValueChanged:(id)sender {
    if (_msgCode.text.length && _pwdText.text.length && _agreeBtn.selected) {
        _registerBtn.backgroundColor = BLUE_COLOR;
        _registerBtn.userInteractionEnabled = YES;
    } else {
        _registerBtn.backgroundColor = UNUSEABLECOLOR;
        _registerBtn.userInteractionEnabled = NO;
    }
}

- (void)sendCodeClick {
    _sendCode.userInteractionEnabled = NO;
    _sendCode.layer.borderWidth = 0;
    _sendCode.textColor = GRAYCOLOR;
   
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Index/getMobileVerifyCode";
    request.params = @{@"mobile":_telNum,
                       @"sms_type":@1};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
          timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
            JSSHOW(model.msg);
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
    }];
}

- (void)countDown {
    if (!timeCount) {
        [timer invalidate];
        _sendCode.userInteractionEnabled = YES;
        _sendCode.layer.borderWidth = 1;
        _sendCode.textColor = BLUE_COLOR;
        _sendCode.text = @"重新发送";
        timeCount = timeOutLine;
        return;
    }
    _sendCode.text = [NSString stringWithFormat:@"%ld秒后重发",timeCount];
    timeCount--;
}

/**
 * 功能： 判断长度大于6位小于20位并是否同时包含且只有数字和字母
 */
- (BOOL)judgePassWordLegal:(NSString *)text{
    BOOL result = false;
    if ([text length] >= 6){
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:text];
    }
    return result;
}
@end
